package cc.ufinity.networkdiagnose.widget;

import java.util.Timer;
import java.util.TimerTask;

import cc.ufinity.networkdiagnose.manager.FTPConfig;
import cc.ufinity.networkdiagnose.manager.MessageWhat;
import cc.ufinity.networkdiagnose.manager.NetworkManager;
import cc.ufinity.networkdiagnose.manager.PullTaskParser;
import cc.ufinity.networkdiagnose.manager.Task;
import cc.ufinity.networkdiagnose.manager.TaskParser;
import cc.ufinity.networkdiagnose.manager.WlanManager;
import cc.ufinity.networkdiagnose.util.StringUtils;
import cc.ufinity.networkdiagnose.view.R;
import android.app.Activity;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.net.wifi.ScanResult;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

public class SegregateTestWidgetProxy extends GeneralTestWidget {

    // private WlanManager wlanManager;
    private Activity ctx;
    private Handler handler;
    private Button btnBack;
    private Button btnStart;
    private EditText ipText;
    private int frequency = 10;
    private NetworkManager nm;
    private ScrollView sv;
    private LinearLayout resultLayout;
    private boolean processing;
    private int current;
    private int successTimes;
    private Task task;

    public SegregateTestWidgetProxy(Activity context) {
        super(context);
        inflate(context, R.layout.segregate_test_widget_proxy, this);
        this.ctx = context;
        btnBack = (Button) this.findViewById(R.id.segregate_test_proxy_btnback);
        btnStart = (Button) this.findViewById(R.id.btn_segregate_proxy_start);
        sv = (ScrollView) this.findViewById(R.id.segregate_test_proxy_ScrView);
        resultLayout = (LinearLayout) this.findViewById(R.id.segregate_test_proxy_layout);
        ipText = (EditText) this.findViewById(R.id.text_segregateTest_proxy_pingaddress);
        btnStart.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                startTest();
            }
        });

        btnBack.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                backToTask(ctx);
            }
        });

        handler = new Handler() {
            public void handleMessage(Message msg) {
                switch (msg.what) {
                case MessageWhat.DO_NEXT_TEST:
                    showNextText();
                    break;
                default:
                    updateResult(msg.what);
                    break;
                }
            }
        };

        // wlanManager = new WlanManager(ctx);
        nm = new NetworkManager();
        nm.setHandler(handler);
        // wlanManager.setHandler(handler);
        task = (Task) ctx.getIntent().getSerializableExtra(TAG_REFER_TASK);
        frequency = task.testCount;
    }

    private void showNextText() {
        RoamTestWidgetProxy rwp = new RoamTestWidgetProxy(ctx);
        ctx.setContentView(rwp);

    }

    private void doNextTest() {
        TimerTask timerTask = new TimerTask() {
            @Override
            public void run() {
                sendMsg(MessageWhat.DO_NEXT_TEST, handler);
            }
        };
        Timer t = new Timer();
        t.schedule(timerTask, TASK_PERFORM_INTERVAL);
        this.showMessage(ctx, "隔离认证测试已完成，10秒后进入下一环节.");
    }

    /**
     * 用户隔离PING测试
     */
    private void startTest() {
        processing = false;
        current = 0;
        successTimes = 0;
        resultLayout.removeAllViews();
        final String ip = ipText.getText().toString();
        if (StringUtils.isIPV4(ip)) {
            final FTPConfig ftp = this.getFTPConfig(ctx);
            if (ftp != null) {
                this.showProgressDialog(ctx, "正在进行隔离测试...", frequency);
                new Thread() {
                    public void run() {
                        while (current < frequency) {
                            if (!processing) {
                                processing = true;
                                current++;
                                nm.ping(ip, 1, 64);
                            }
                        }
                    }
                }.start();
            }
        } else {
            this.showMessage(ctx, "请输入正确的IPV4地址!");
        }
    }

    private void updateResult(int msgWhat) {
        this.setDialogProgress(current);
        String res = nm.getPingResult();
        TextView tv = null;
        switch (msgWhat) {
        case MessageWhat.PING_SUCCESS:
            tv = new TextView(ctx);
            tv.setText(res);
            tv.setTextSize(12);
            resultLayout.addView(tv);
            break;
        case MessageWhat.PING_FAILED:
            successTimes++;
            StringBuffer s = new StringBuffer();
            s.append("第").append(current).append("次 PING测试失败");
            tv = new TextView(ctx);
            tv.setText(res);
            tv.setTextSize(12);
            tv.setText(s);
            resultLayout.addView(tv);
        }
        processing = false;
        if (current == frequency) {
            StringBuffer s = new StringBuffer();
            s.append("隔离测试总数：").append(frequency);
            s.append(" 隔离成功率：").append((successTimes / frequency) * 100).append('%');
            tv = new TextView(ctx);
            tv.setTextSize(13);
            tv.setTextColor(Color.CYAN);
            tv.setText(s);
            resultLayout.addView(tv);

            task.userIsolateSuccessRate = String.valueOf((successTimes / frequency) * 100);
            ctx.getIntent().putExtra(TAG_REFER_TASK, task);

            dismissProgressDialog();
            doNextTest();
        }
        this.setScrollViewDown(sv);

    }

}
